package com.hw.paltfrom.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PageUtils<T> {
	private Integer pageNum;
	private Integer pageSize;
	private Integer total;
	private List<T> data;

	public PageUtils(Integer pageNum, Integer pageSize) {
		this.pageSize = pageSize;
		this.pageNum = pageNum;
	}

	public Object getPageResult(List<T> list) {
		
		HashMap<String, Object> result = new HashMap<String, Object>();
		int total = list.size();
		if(list.isEmpty()){
			result.put("total", total);
			result.put("pageNum", pageNum);
			result.put("pageSize", pageSize);
			result.put("data", data);
			
			return result;
		}else{
			List<List<T>> fixedGrouping = fixedGrouping(list,pageSize);
			List<T> data = fixedGrouping.get(pageNum-1);
			
			result.put("total", total);
			result.put("pageNum", pageNum);
//			result.put("pageSize", data.size());
			result.put("pageSize", pageSize);
			result.put("data", data);
			return result;
		}
		
	}
	private static <T> List<List<T>> fixedGrouping(List<T> source, int n) {

	    if (null == source || source.size() == 0 || n <= 0)
	        return null;
	    List<List<T>> result = new ArrayList<List<T>>();

	    int sourceSize = source.size();
	    int size = (source.size() / n) + 1;
	    for (int i = 0; i < size; i++) {
	        List<T> subset = new ArrayList<T>();
	        for (int j = i * n; j < (i + 1) * n; j++) {
	            if (j < sourceSize) {
	                subset.add(source.get(j));
	            }
	        }
	        result.add(subset);
	    }
	    return result;
	}

	public Integer getPageNum() {
		return pageNum;
	}

	public void setPageNum(Integer pageNum) {
		this.pageNum = pageNum;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public List<T> getData() {
		return data;
	}

	public void setData(List<T> data) {
		this.data = data;
	}
	
	
	
}
